﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.ServiceModel;
using System.Net;
using Infragistics.Win.UltraWinGrid;



namespace DMSClient.Distributors
{
    public partial class Orders : Form
    {

        private DMSServices.DMSServicesClient client;
        private DataTable dt;
        DataTable dtOrderInvoice;
        DataTable dtOrderInvoice_AUD;
        DataTable dtOrderInvoiceDetails;
        string fileNameToExportPDF = "";
        static bool fileExported = false;
        private string ambient;
        private string idDistributor = "";
        private string cdDistributor = "";
        private string dtInvoiceStart = "";
        private string dtInvoiceEnd = "";

        public Orders()
        {
            InitializeComponent();
            this.ambient = Properties.Settings.Default.CurrentEnv;
            this.Text = this.ambient + " - Orders Report";

            WSHttpBinding Binding = new WSHttpBinding();
            Binding.MaxReceivedMessageSize = Int32.MaxValue;
            Binding.MaxBufferPoolSize = Int32.MaxValue;
            Binding.CloseTimeout = TimeSpan.MaxValue;
            Binding.ReceiveTimeout = TimeSpan.MaxValue;
            Binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            Binding.Security.Mode = SecurityMode.None;

            EndpointAddress address = new EndpointAddress(Properties.Settings.Default.Server);
            client = new DMSServices.DMSServicesClient(Binding, address);
        }

        private void Orders_Load(object sender, EventArgs e)
        {
            uceDistributors.DisplayMember = "cdOrgUnit";
            uceDistributors.ValueMember = "idOrgUnit";          

            string respuesta = client.getDistributorsList(this.ambient);

            dt = new DataTable("dtDistributorsList");
            dt.Columns.Add("idOrgUnit", Type.GetType("System.Int16"));
            dt.Columns.Add("cdOrgUnit", Type.GetType("System.String"));

            DataSet dataSet = new DataSet();
            dataSet.Tables.Add(dt);
            System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
            dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();

            uceDistributors.DataSource = dt;
            uceDistributors.SelectedIndex = 0;
        }

        private void cargarGrid()
        {
             idDistributor = uceDistributors.Value.ToString();
             cdDistributor = uceDistributors.Text.ToString();
             dtInvoiceStart = udteStartDate.Value.ToString();
             dtInvoiceEnd = udteEndDate.Value.ToString();
             //-
             DateTime INI_F = DateTime.Parse(dtInvoiceStart);
             DateTime FIN_F = DateTime.Parse(dtInvoiceEnd);
             dtInvoiceStart = INI_F.Date.ToShortDateString();
             dtInvoiceEnd = FIN_F.Date.ToShortDateString();


             WSHttpBinding binding = new WSHttpBinding();
             binding.CloseTimeout = new TimeSpan(0, 1, 0);
             binding.OpenTimeout = new TimeSpan(0, 1, 0);
             binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
             binding.SendTimeout = new TimeSpan(0, 1, 0);
             binding.MaxReceivedMessageSize = Int32.MaxValue;
             binding.MaxBufferPoolSize = Int32.MaxValue;
             binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
             binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
             binding.Security.Mode = SecurityMode.None;



             EndpointAddress address = new EndpointAddress(Properties.Settings.Default.Server);
             DMSServices.DMSServicesClient service = new DMSServices.DMSServicesClient(binding, address);
             DMSServices.DMSServicesClient serviceII = new DMSServices.DMSServicesClient(binding, address);

             string respuesta = null;

             //--DATOS ORDEN
             try
             {
                 service.Open();
                 //"|2" para que el modo de consulta consulte por las fechas de ORDERS
                 respuesta = service.getOInvoiceReport(idDistributor + "|2", INI_F, FIN_F, this.ambient);
                 service.Close();
                 respuesta = Compression.Decompress(respuesta);

                 dtOrderInvoice = new DataTable("dtOInvoiceReport");
                 dtOrderInvoice.Columns.Add("cdOrder");
                 dtOrderInvoice.Columns.Add("cdCreationUser");
                 dtOrderInvoice.Columns.Add("cdStore");
                 dtOrderInvoice.Columns.Add("cdRegion");
                 dtOrderInvoice.Columns.Add("dtOrder", typeof(DateTime));
                 dtOrderInvoice.Columns.Add("vlDiscountTotal");
                 dtOrderInvoice.Columns.Add("vlTotalOrder");
                 dtOrderInvoice.Columns.Add("vlTotalUnit");
                 dtOrderInvoice.Columns.Add("cdRoute");
                 dtOrderInvoice.Columns.Add("cdStatusOrder");
                 dtOrderInvoice.Columns.Add("cdInvoice");
                 dtOrderInvoice.Columns.Add("dsDisplayText");
                 dtOrderInvoice.Columns.Add("dtInvoice");
                 dtOrderInvoice.Columns.Add("vlTotalInvoice");
                 dtOrderInvoice.Columns.Add("nrTotalQuantity");
                 dtOrderInvoice.Columns.Add("cdStatusInvoice");

                 DataSet dataSet = new DataSet("dsOInvoiceReport");
                 dataSet.Tables.Add(dtOrderInvoice);
                 System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
                 dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
                 xmlSR.Close();                 
             }
             catch (Exception ex)
             {
                 throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
             }           
             //--DATOS AUDITORIA
             #region
            /*
             respuesta = null;
             try
             {
                 serviceII.Open();
                 respuesta = serviceII.getOrderInvoice_AUD_Report( cdDistributor, "1", DateTime.Parse(dtInvoiceStart), DateTime.Parse(dtInvoiceEnd), this.ambient);
                 serviceII.Close();
                 respuesta = Compression.Decompress(respuesta);

                 dtOrderInvoice_AUD = new DataTable("dtImportOrderInvoice_AUD");
                 dtOrderInvoice_AUD.Columns.Add("distributor");
                 dtOrderInvoice_AUD.Columns.Add("errors");
                 dtOrderInvoice_AUD.Columns.Add("display");
                 dtOrderInvoice_AUD.Columns.Add("iddoc");
                 dtOrderInvoice_AUD.Columns.Add("docfecha");
                 dtOrderInvoice_AUD.Columns.Add("idproduct");
                 dtOrderInvoice_AUD.Columns.Add("idstore");
                 dtOrderInvoice_AUD.Columns.Add("idregion");
                 dtOrderInvoice_AUD.Columns.Add("nrQuantity");
                 dtOrderInvoice_AUD.Columns.Add("vlDiscount");
                 dtOrderInvoice_AUD.Columns.Add("vltotal");
                 dtOrderInvoice_AUD.Columns.Add("estatus");


                 DataSet dataSet = new DataSet("dsImportOrderInvoice_AUD");
                 dataSet.Tables.Add(dtOrderInvoice_AUD);
                 System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
                 dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
                 xmlSR.Close();
             }
             catch (Exception ex)
             {
                 throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
             }
            */
            #endregion
        }

        private void bgWorker_Consulta_DoWork(object sender, DoWorkEventArgs e)
        {
            cargarGrid();
        }

        private void uceDistributors_ValueChanged(object sender, EventArgs e)
        {
            ugOrderInvoive.DataSource = null;
            ugOrderInvoive.DataBind();
        }

        private void bgWorker_Consulta_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {                        
            if (!this.IsDisposed)
            {
                    //Cargar datos de la orden
                    dtOrderInvoice.AcceptChanges();
                    ugOrderInvoive.DataSource = dtOrderInvoice;
                    ugOrderInvoive.DataBind();
                    //Cargar datos para la vista de interfaz                   
                    ug_interfaceView.DataSource = dtOrderInvoice;
                    ug_interfaceView.DataBind();

                    //ug_interfaceView.DisplayLayout.Bands[0].Columns["cdInvoice"].GroupByRowAppearance.BackColor = Color.AliceBlue;
                //.Override.ActiveCellAppearance.BackColor=Color.AliceBlue;   .Columns["cdInvoice"].Style

                    //Ocultando columnas de INVOICE pero que q tienen datos necesarios
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["cdInvoice"].Hidden = true;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["dsDisplayText"].Hidden = true;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["nrTotalQuantity"].Hidden = true;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["vlTotalInvoice"].Hidden = true;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["dtInvoice"].Hidden = true;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["cdStatusInvoice"].Hidden = true;
                    //-        
                    //-Reporte de auditoria               
                    //dtOrderInvoice_AUD.AcceptChanges();
                    //ugAUD_Orders.DataSource = dtOrderInvoice_AUD;
                    //ugAUD_Orders.DataBind();
                                                                                                        
                    activarControles(true);
            }
            else if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activarControles(true);
                }
            }
        }

        private void activarControles(bool value)
        {
            loader.Visible = !value;
            ultraGroupBox1.Enabled = value;
            ugOrderInvoive.Enabled = value;
        }

        private void ultraButton1_Click(object sender, EventArgs e)
        {
            //Verificamos consultas máximo para 12 meses para que no se pifie esta...
            int currenNrodays = 0;
            if (365 < (currenNrodays = DateTime.Parse(udteEndDate.Value.ToString()).Subtract(DateTime.Parse(udteStartDate.Value.ToString())).Days))
            {
                MessageBox.Show("Maximum range of dates to see: 12 months : 365 Days. Your selected: " + currenNrodays.ToString() + " Days.");
                return;
            }
            else if (currenNrodays < 0)
            {
                MessageBox.Show("Start date greater than end date.");
                return;
            }
            bgWorker_Consulta.RunWorkerAsync();
            activarControles(false);
        }


        private void bntExport_Click(object sender, EventArgs e)
        {
            if (ugOrderInvoive.Rows.Count < 1)
            {
                MessageBox.Show(this, "There is no data to export", "Orders Report", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (MessageBox.Show(this, "The data will be exported interface view. Continue?", "Orders Report", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                System.Windows.Forms.SaveFileDialog dialogo = new System.Windows.Forms.SaveFileDialog();
                dialogo.DefaultExt = "pdf";
                dialogo.Filter = ". pdf | (Pdf File)";
                if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    activarControles(false);
                    fileNameToExportPDF = dialogo.FileName;
                    bgWorker_Consulta.CancelAsync();
                    bgWorker_EXPORT.RunWorkerAsync();
                }
            }
            else
            {
                return;
            }              
        }


        private void bgWorker_EXPORT_DoWork(object sender, DoWorkEventArgs e)
        {
            PDFExport d = new PDFExport(PDFExport_F);
            this.Invoke(d, new object[] { fileNameToExportPDF });
        }

        //Delegado para poder acceder a controles en el DoWork
        delegate void PDFExport(string nombreYrutaPDF);

        /*Exporta a PDF*/
        private void PDFExport_F(string nombreYrutaPDF)
        {
            loader.Visible = true;
            try
            {
                this.ultraGridDocumentExporter1.Export(ug_interfaceView, nombreYrutaPDF, Infragistics.Win.UltraWinGrid.DocumentExport.GridExportFileFormat.PDF);
                fileExported = true;
            }
            catch (Exception Ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, Ex.InnerException);
            }
            return;
        }

        private void bgWorker_EXPORT_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!this.IsDisposed)
            {
                activarControles(true);
                if (fileExported)
                {
                    fileExported = false;
                    System.Diagnostics.Process.Start(fileNameToExportPDF);
                }
            }
            else if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activarControles(true);
                }
            }            
        }

        private void ugOrderInvoive_AfterSelectChange(object sender, Infragistics.Win.UltraWinGrid.AfterSelectChangeEventArgs e)
        {            
            /*
             
            Infragistics.Win.UltraWinGrid.UltraGrid grid = (Infragistics.Win.UltraWinGrid.UltraGrid)sender;           
            string [] dataHead= new  string[12];
            //ENCABEZADOS DE LA ORDEN
            dataHead[0] = grid.ActiveRow.Cells["cdOrder"].Value.ToString(); //cod ERP    = cdOrder
            dataHead[1] = grid.ActiveRow.Cells["cdRegion"].Value.ToString();//region      = cdRegion
            dataHead[2] = grid.ActiveRow.Cells["vlDiscountTotal"].Value.ToString();//total descuento = vlDiscountTotal
            dataHead[3] = grid.ActiveRow.Cells["vlTotalOrder"].Value.ToString();//valor total     = vlTotalOrder
            dataHead[4] = grid.ActiveRow.Cells["dtOrder"].Value.ToString();//fecha Orden   =     dtOrder                
            dataHead[5] = grid.ActiveRow.Cells["cdStatusOrder"].Value.ToString();//estado orden  =      cdStatusOrder                
            //ENCABEZADOS DE INVOICE                        
            dataHead[6] = grid.ActiveRow.Cells["cdInvoice"].Value.ToString(); //cod Documento   = cdInvoice
            dataHead[7] = grid.ActiveRow.Cells["dsDisplayText"].Value.ToString();//Descripcion     = dsDisplayText
            dataHead[8] = grid.ActiveRow.Cells["nrTotalQuantity"].Value.ToString();//total productos = nrTotalQuantity
            dataHead[9] = grid.ActiveRow.Cells["vlTotalInvoice"].Value.ToString();//valor total     = vlTotalInvoice
            dataHead[10] = grid.ActiveRow.Cells["dtInvoice"].Value.ToString();//fecha factura   = dtInvoice                     
            dataHead[11] = grid.ActiveRow.Cells["cdStatusInvoice"].Value.ToString();//estado factura   = dtInvoice                     

            OrderInvoiceDetails frmDetails = new OrderInvoiceDetails(idDistributor, dtInvoiceStart, dtInvoiceEnd, dataHead[6].ToString().Trim(), ambient, dataHead);
            frmDetails.ShowDialog();

            */


        }

        private void ugOrderInvoive_DoubleClick(object sender, EventArgs e)
        {
            Infragistics.Win.UltraWinGrid.UltraGrid grid = (Infragistics.Win.UltraWinGrid.UltraGrid)sender;
            Infragistics.Win.UIElement element = grid.DisplayLayout.UIElement.LastElementEntered;
            Infragistics.Win.UltraWinGrid.UltraGridCell cell = element.GetContext(typeof(Infragistics.Win.UltraWinGrid.UltraGridCell)) as Infragistics.Win.UltraWinGrid.UltraGridCell;

            if (cell != null)
            {                
                string[] dataHead = new string[13];
                //ENCABEZADOS DE LA ORDEN
                dataHead[0] = grid.ActiveRow.Cells["cdOrder"].Value.ToString(); //cod ERP    = cdOrder
                dataHead[1] = grid.ActiveRow.Cells["cdRegion"].Value.ToString();//region      = cdRegion
                dataHead[2] = grid.ActiveRow.Cells["vlDiscountTotal"].Value.ToString();//total descuento = vlDiscountTotal
                dataHead[3] = grid.ActiveRow.Cells["vlTotalOrder"].Value.ToString();//valor total     = vlTotalOrder                
                dataHead[4] = grid.ActiveRow.Cells["dtOrder"].Value.ToString();//fecha Orden   =     dtOrder                
                dataHead[5] = grid.ActiveRow.Cells["cdStatusOrder"].Value.ToString();//estado orden  =      cdStatusOrder                
                dataHead[6] = grid.ActiveRow.Cells["vlTotalUnit"].Value.ToString();//numero total de lineas en la oren =  vlTotalUnit
                //ENCABEZADOS DE INVOICE                        
                dataHead[7] = grid.ActiveRow.Cells["cdInvoice"].Value.ToString(); //cod Documento   = cdInvoice
                dataHead[8] = grid.ActiveRow.Cells["dsDisplayText"].Value.ToString();//Descripcion     = dsDisplayText
                dataHead[9] = grid.ActiveRow.Cells["nrTotalQuantity"].Value.ToString();//total productos = nrTotalQuantity
                dataHead[10] = grid.ActiveRow.Cells["vlTotalInvoice"].Value.ToString();//valor total     = vlTotalInvoice
                dataHead[11] = grid.ActiveRow.Cells["dtInvoice"].Value.ToString();//fecha factura   = dtInvoice                     
                dataHead[12] = grid.ActiveRow.Cells["cdStatusInvoice"].Value.ToString();//estado factura   = dtInvoice                     
                //modoConsulta:
                //"|1" para que el modo de consulta consulte por las fechas de INVOICES
                //"|2" para que el modo de consulta consulte por las fechas de ORDERS 
                OrderInvoiceDetails frmDetails = new OrderInvoiceDetails(idDistributor, dtInvoiceStart, dtInvoiceEnd, dataHead[7].ToString().Trim(), ambient, dataHead,"2");
                frmDetails.MdiParent = this.ParentForm;
                frmDetails.Show();

            }
        }

        private void Orders_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bgWorker_EXPORT.IsBusy)
            {
                bgWorker_EXPORT.CancelAsync();
            }

            if (bgWorker_Consulta.IsBusy)
            {
                bgWorker_Consulta.CancelAsync();
            }
        }

        private void ultraTabPageControl2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Orders_Shown(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void Orders_Resize(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void ugOrderInvoive_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {          
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
        }

        private void Orders_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)27)
            {
                this.Close();
            }
        }

        private void ugOrderInvoive_InitializeRow(object sender, InitializeRowEventArgs e)
        {
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                e.Row.Cells[i].ToolTipText = "Double Click for Details";               
            }
        }

        private void ug_interfaceView_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
        }

        private void ug_OrderItemsInvoiceItems_interfaceView_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
        }

        private void ug_interfaceView_InitializeRow(object sender, InitializeRowEventArgs e)
        {
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                e.Row.Cells["cdOrder"].Appearance.BackColor = Color.SkyBlue;
                e.Row.Cells["cdInvoice"].Appearance.BackColor = Color.SkyBlue;                               
            }
        }     
    }
}
